<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use App\Mail\TicketAvailableNotification;
use Carbon\Carbon;

class CheckTicketAvailabilityCommand extends Command
{
    /**
     * 命令名称
     *
     * @var string
     */
    protected $signature = 'ticket:check';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '检查江西博物馆余票情况（2025-10-03和2025-10-07）';

    /**
     * 查询接口URL
     */
    private const API_URL = 'https://ticket.jxmuseum.cn:4430/api/sw-dam/personalReserve/queryPersonal';

    /**
     * 目标查询日期
     */
    private const TARGET_DATES = ['2025-10-03'];

    /**
     * 执行命令
     */
    public function handle()
    {
        $currentTime = Carbon::now();
        $this->info('开始检查余票情况 - ' . $currentTime->toDateTimeString());

        // 检查是否已过期（2025年10月7日后停止检查）
        if ($currentTime->gt(Carbon::parse('2025-10-03 23:59:59'))) {
            $this->info('已过2025年10月7日，停止余票检查');
            return;
        }

        try {
            // 调用查询接口
            $response = $this->queryTicketAvailability();

            if ($response) {
                $this->processTicketData($response);
            } else {
                $this->error('查询接口调用失败');
                Log::error('余票查询接口调用失败', [
                    'time' => $currentTime->toDateTimeString(),
                    'url' => self::API_URL
                ]);
            }

        } catch (\Exception $e) {
            $this->error('余票查询出现异常: ' . $e->getMessage());
            Log::error('余票查询异常', [
                'time' => $currentTime->toDateTimeString(),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }

    /**
     * 查询余票接口
     */
    private function queryTicketAvailability()
    {
        try {
            $response = Http::timeout(30)->post(self::API_URL);

            if ($response->successful()) {
                $data = $response->json();

                if (isset($data['code']) && $data['code'] == 200) {
                    return $data['data'] ?? [];
                } else {
                    $this->error('接口返回错误: ' . ($data['msg'] ?? '未知错误'));
                    Log::error('余票查询接口返回错误', [
                        'response' => $data,
                        'time' => Carbon::now()->toDateTimeString()
                    ]);
                    return null;
                }
            } else {
                $this->error('HTTP请求失败，状态码: ' . $response->status());
                Log::error('余票查询HTTP请求失败', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                    'time' => Carbon::now()->toDateTimeString()
                ]);
                return null;
            }
        } catch (\Exception $e) {
            $this->error('请求异常: ' . $e->getMessage());
            Log::error('余票查询请求异常', [
                'error' => $e->getMessage(),
                'time' => Carbon::now()->toDateTimeString()
            ]);
            return null;
        }
    }

    /**
     * 处理余票数据
     */
    private function processTicketData($data)
    {
        $availableTickets = [];

        foreach ($data as $dayData) {
            $dayTime = $dayData['dayTime'] ?? '';

            // 只检查目标日期
            if (in_array($dayTime, self::TARGET_DATES)) {
                $surplusList = $dayData['surplusList'] ?? [];

                foreach ($surplusList as $surplus) {
                    $surplusCount = $surplus['surplusCount'] ?? 0;

                    if ($surplusCount > 0) {
                        $availableTickets[] = [
                            'date' => $dayTime,
                            'time_slot' => $surplus['intervalValue'] ?? '',
                            'available_count' => $surplusCount,
                            'total_count' => $surplus['totalCount'] ?? 0
                        ];
                    }
                }
            }
        }

        // 输出结果
        if (empty($availableTickets)) {
            $this->info('暂无余票');
        } else {
            $this->info('发现余票！');
            foreach ($availableTickets as $ticket) {
                $info = sprintf(
                    '日期: %s, 时段: %s, 余票: %d/%d',
                    $ticket['date'],
                    $ticket['time_slot'],
                    $ticket['available_count'],
                    $ticket['total_count']
                );
                $this->line($info);
            }

            // 记录到日志
            Log::info('发现余票', [
                'tickets' => $availableTickets,
                'time' => Carbon::now()->toDateTimeString()
            ]);

            // 这里可以添加通知逻辑，比如发送邮件、微信通知等
            $this->sendNotification($availableTickets);
        }
    }

    /**
     * 发送通知
     */
    private function sendNotification($availableTickets)
    {
        try {
            // 获取通知邮箱地址，可以从配置文件或环境变量中获取

            $notificationEmail = config('mail.notify_recipient');

            if ($notificationEmail) {
                // 发送邮件通知
                Mail::to($notificationEmail)->send(new TicketAvailableNotification($availableTickets));

                $this->info('邮件通知已发送到: ' . $notificationEmail);
                Log::info('余票邮件通知发送成功', [
                    'email' => $notificationEmail,
                    'tickets_count' => count($availableTickets),
                    'time' => Carbon::now()->toDateTimeString()
                ]);
            } else {
                $this->warn('未配置通知邮箱地址，跳过邮件通知');
            }

        } catch (\Exception $e) {
            $this->error('邮件通知发送失败: ' . $e->getMessage());
            Log::error('余票邮件通知发送失败', [
                'error' => $e->getMessage(),
                'tickets' => $availableTickets,
                'time' => Carbon::now()->toDateTimeString()
            ]);
        }
    }
}
